var multer = require('koa-multer')
const config = require('../config.js');
const fs = require('fs');
const tools = require('../common/index.js');

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, config.imageDir)
    },
    filename: function (req, file, cb) {
        cb(null, 'blog-image-' + Date.now() + '.' + file.originalname.split('.').slice(-1))
    }
});
var upload = multer({storage: storage})

module.exports = {
    'POST /uploadImg': async (ctx, next) => {
        let err = await upload.single('avatar')(ctx, next)
            .then(res => res)
            .catch(err => err)
        if(err){
            ctx.response.status = 499;
            ctx.response.message = 'image upload failed:'+err.code;
        }else{
            console.log(ctx)
            ctx.response.body = ctx.req.file.filename;
        }
    },
    'GET /downloadImg/:filename': async (ctx, next) => {
        let name = ctx.params.filename;
        let extension = name.split('.').slice(-1)[0].toLowerCase();
        if (extension != 'gif' && extension != 'png' && extension != 'jpeg') {
            ctx.response.status = 497;
            ctx.response.message = 'not a image file';
        } else {
            try {
                ctx.response.type = 'image/' + extension;
                ctx.response.body = fs.readFileSync(config.imageDir + '/' + name);
            } catch (err) {
                ctx.response.status = 498;
                ctx.response.message = 'no such file exists or download failed';
            }
        }
    }
};